/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package th.stripes;

/**
 *
 * @author fikri
 */
import able.stripes.JSP;
import com.google.inject.Inject;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;
import th.dao.SejarahTransaksiDAO;
import th.manager.SejarahTransaksiManager;
import th.manager.SequenceManager;
import th.manager.UserManager;
import th.model.Pengguna;
import th.model.SejarahTransaksi;
import th.model.SeqNum;
import th.service.session.SessionManager;

@UrlBinding("/logout")
public class LogoutActionBean extends BaseActionBean {
    
    private Pengguna pguna;
    @Inject
    private SejarahTransaksiDAO sejarahTransaksiDAO;
    @Inject
    private SejarahTransaksiManager sejarahTransaksiManager;
    @Inject
    Configuration conf;
    
    @Inject UserManager userManager;
    
    @Inject SequenceManager sequenceManager;
    
    private String counter;
    
    private static String MSG_ID = "counter";
    
    
    @DefaultHandler
    public Resolution logout() {
        HttpSession ses = context.getRequest().getSession();
        //return new RedirectResolution(WelcomeActionBean.class);
        Pengguna pengguna = getContext().getCurrentUser();
        if(pengguna==null){
            addMessage("Maaf, sessi sudah luput.");
            return new RedirectResolution(WelcomeActionBean.class);
        }
        
         counter = getContext().getCounter();
            if ("".equals(counter) || counter == null) {
            doCount();
        }
            
        Date d = (Date)ses.getAttribute("_TRH_LOGIN"); 
        if ( d != null) {
            pengguna.setTarikhAkhirLogin(d);
            userManager.updatePengguna(pengguna);
        }
            
        List listst = sejarahTransaksiManager.findSejarahTransaksiBySessionId(pengguna.getNoKp(), ses.getId());
        
        
            getContext().getServletContext().setAttribute("listSt", listst);            
            getContext().getServletContext().setAttribute("Pengguna", pengguna);
            SessionManager sm = SessionManager.getInstance();
                sm.removeSession(ses.getId());
                _logout();
                if (ses != null) {
                    ses.invalidate();
                }

        if(listst!=null && listst.size()>0){
            getContext().getRequest().getSession().setAttribute("listSt", listst);         
            getContext().getRequest().getSession().setAttribute("Pengguna", pengguna);
            
           
            
            return new JSP("logout.jsp");
        }else{                
            return new RedirectResolution(WelcomeActionBean.class);
        }
        
    }   
    
     private void doCount() {
        counter = sequenceManager.getSequenceWithoutLeadingZero(MSG_ID);
        SeqNum seqNum = new SeqNum();
        seqNum.setNum(Integer.parseInt(counter));
        seqNum.setUrusan(MSG_ID);  
        sequenceManager.updateCounter(seqNum);
        
        HttpSession ses = getContext().getRequest().getSession();

        ses.setAttribute(th.stripes.config.ableActionBeanContext.COUNTER_ID_KEY, counter);
    }


    private void _logout() {
        getContext().logout();
        addMessage("loggedOut");
    }
    
    public Resolution logoutReport() throws Exception {


        //Pengguna pengguna = getContext().getCurrentUser();
        Pengguna pengguna = (Pengguna) getContext().getServletContext().getAttribute("Pengguna");

        SimpleDateFormat d = new SimpleDateFormat("dd/MM/yyyy");
        SimpleDateFormat t = new SimpleDateFormat("HH:mm:ss");

        List list = new ArrayList();
        List listst = (List) getContext().getServletContext().getAttribute("listSt");
        if (listst != null) {
            for (int i = 0; i < listst.size(); i++) {

                Map map1 = new HashMap();
                SejarahTransaksi st = (SejarahTransaksi) listst.get(i);
                map1.put("ID Transaksi", st.getNilaiDalaman1());
                map1.put("Transaksi", st.getUrusan().getNama());
                String dt = d.format(st.getTrhMasuk());
                map1.put("Tarikh Transaksi", dt);
                String tm = t.format(st.getTrhMasuk());
                map1.put("Masa Transaksi", tm);
                if (st.getStatus().getKod().equals("0000")) {
                    map1.put("Status", "BERJAYA");
                } else {
                    map1.put("Status", "TIDAK BERJAYA");
                }
                list.add(map1);
            }
        }
        Map map = new HashMap();
        map.put("tlist", list);
        map.put("User ID", pengguna.getIdPengguna());

        String dtl = d.format(pengguna.getTarikhAkhirLogin());
        map.put("Tarikh Login", dtl);
        String tml = t.format(pengguna.getTarikhAkhirLogin());
        map.put("Masa Login", tml);

        String reportpath = conf.getProperty("report.path");
        map.put("SUBREPORT_DIR", reportpath);
        map.put("REPORT_DIR", reportpath);

        //  JasperPrint jasperPrint = JasperFillManager.fillReport(reportpath+"SuratPenerbanganJH.jasper", map,new JREmptyDataSource());
        JasperPrint jasperPrint1 = JasperFillManager.fillReport(reportpath + "logout_report.jasper", map, new JREmptyDataSource());
        byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint1);
        InputStream is = new ByteArrayInputStream(bytes);

//      return new StreamingResolution("application/pdf") {
//
//            @Override
//            public void stream(HttpServletResponse response) throws Exception {
////                response.setHeader("Cache-Control", "no-cache");
////                response.setHeader("Pragma", "no-cache");
////                response.setDateHeader("Expires", 0);
////                response.setContentType("application/pdf");
////                response.setHeader("Content-disposition", "inline; filename=test.pdf");
////                ServletOutputStream out = response.getOutputStream();
////                out.write(bytes);
////                out.flush();
////                out.close();
//                InputStream inputStream = new ByteArrayInputStream(bytes);
//                BufferedInputStream bis = new BufferedInputStream(inputStream);
//                ByteArrayOutputStream bous = new ByteArrayOutputStream();
//                
//                int ch;
//                while ((ch = bis.read()) != -1) {
//                    bous.write(ch);
//                }
//                bous.writeTo(response.getOutputStream());
//            }
//        }.setFilename("logout_report");

        return new StreamingResolution("application/pdf", is);
    }

    public Pengguna getPguna() {
        return pguna;
    }

    public void setPguna(Pengguna pguna) {
        this.pguna = pguna;
    }



}
